﻿
#include "event_loop.h"
#include "Poco/NObserver.h"
#include "ZsLog.h"

zs::CEventLoop::CEventLoop()
{
    reactor_ = std::make_unique<Poco::Net::SocketReactor>();
}

zs::CEventLoop::~CEventLoop()
{
    reactor_->stop();
}

void zs::CEventLoop::run()
{
    reactor_->run();
}

void zs::CEventLoop::stop()
{
    reactor_->stop();
}

void zs::CEventLoop::register_timer_event(long interval, TimerCallback timer_cb)
{
    timers_.emplace_back(std::make_unique<zs::CZSTimer>(interval, std::move(timer_cb)));
}

void zs::CEventLoop::add_write_event_handler(const Poco::Net::Socket& socket, zs::SkWriteEventHandler write_event_handler)
{
    write_event_handler_ = std::move(write_event_handler);
    reactor_->addEventHandler(socket, Poco::NObserver<zs::CEventLoop, Poco::Net::WritableNotification>(*this, &zs::CEventLoop::event_writable));
}

void zs::CEventLoop::event_writable(const Poco::AutoPtr<Poco::Net::WritableNotification> &pNf)
{
    write_event_handler_();
}

void zs::CEventLoop::event_readable(const Poco::AutoPtr<Poco::Net::ReadableNotification> &pNf)
{
    std::string msg;
    read_event_handler_(msg);
    LOG_INFO << "receive msg from server:\n " << msg;
}

void zs::CEventLoop::add_read_event_handler(const Poco::Net::Socket &socket, zs::SkReadEventHandler read_event_handler)
{
    read_event_handler_ = std::move(read_event_handler);
    reactor_->addEventHandler(socket, Poco::NObserver<zs::CEventLoop, Poco::Net::ReadableNotification>(*this, &zs::CEventLoop::event_readable));
}

void
zs::CEventLoop::remove_event_read_handler(const Poco::Net::Socket &socket)
{
    reactor_->removeEventHandler(socket, Poco::NObserver<zs::CEventLoop, Poco::Net::ReadableNotification>(*this, &zs::CEventLoop::event_readable));
}

void
zs::CEventLoop::remove_event_write_handler(const Poco::Net::Socket &socket)
{
    reactor_->removeEventHandler(socket, Poco::NObserver<zs::CEventLoop, Poco::Net::WritableNotification>(*this, &zs::CEventLoop::event_writable));
}
